<template>
  <div>
    <el-button type="danger" @click="batchDelte" :disabled="isShowDeletaBatchBtn"
      >批量删除</el-button
    >
  
    <!-- <el-button type="success" @click="importData">上传</el-button> -->

    <el-input
      style="width: 200px; margin-left: 20px"
      v-model="state.searchData.name"
      @input="changeSearch"
      clearable
      :prefix-icon="Position"
      placeholder="请输入文件名称"
    />
    <el-input
      style="width: 200px; margin-left: 20px"
      v-model="state.searchData.type"
      @input="changeSearch"
      clearable
      :prefix-icon="ZoomIn"
      placeholder="请输入文件类型"
    />
  </div>
  <div v-if="state.tableData.length > 0">
    <el-table
      :data="state.tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="ID" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="size" label="大小(Kb)" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          
          <!-- <el-button link type="primary" @click="downloadFile(scope.row.url)">下载</el-button> -->
         <a :href="scope.row.url" style="text-decoration: none;margin-right: 15px;">下载</a>
          <el-button link type="primary" @click="goDetail(scope.row.url)">预览</el-button>
          <el-button link type="danger" @click="showDeletePopover(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block mt-3">
      <el-pagination
        v-model:current-page="state.searchData.page"
        v-model:page-size="state.searchData.limit"
        :page-sizes="
          state.searchData.total <= 40
            ? [10, 20, 30, 40]
            : [10, 20, 30, 40, state.searchData.total]
        "
        :disabled="false"
        :background="true"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="state.searchData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <div v-if="state.tableData == ''">
    <el-empty description="暂无相关数据" />
  </div>
  <el-dialog
    v-model="importDataDialogVisible"
    title="提示"
  >
    <el-upload
      name="multipartFile"
      class="upload-demo"
      drag
      :action="UploadFileUrl()"
      :auto-upload="false"
      :on-change="fileChange"
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        你可以将文件拖拽到特定区域以进行上传 <em>或者点击这里</em>
      </div>
      <template #tip>
        <div class="el-upload__tip text-end">
          <el-button class="mt-3" type="primary" @click="uploadFileBtn"
            >立即上传</el-button
          >
        </div>
      </template>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted, markRaw } from "vue";
import { ZoomIn, Position, Delete,UploadFilled } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import router from "../../router";
import request from "../../api/request";
import * as echarts from "echarts";
const state = reactive({
  tableData: [],
  searchData: {
    page: 1,
    limit: 10,
    total: 0,
    name: "",
    type: "",
  },
});

onMounted(() => {
  initData();
});
const isShowDeletaBatchBtn = ref(true);
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  if (multipleSelection._rawValue.length) {
    isShowDeletaBatchBtn.value = false;
  } else {
    isShowDeletaBatchBtn.value = true;
  }
};
const batchDelte = () => {
  console.log(multipleSelection._rawValue.length);
  let ids = multipleSelection._rawValue.map((v) => v.id);
  ElMessageBox.confirm(`您确定删除吗`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      request.post("/files/batch/delete", ids).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: res.msg,
          });
          initData();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

const initData = () => {
  let authentication = localStorage.getItem("adminInfo");
  if (!(authentication == 2)) {
    router.push("/admin/login");
    return;
  }
  request.post("/files/findPage", state.searchData).then((res) => {
    if (res.code == 200) {
      state.tableData = res.data.records;
      state.searchData.total = res.data.total;
    }
  });
};

const handleCurrentChange = (page) => {
  state.searchData.page = page;
  initData();
};
const showDeletePopover = (id) => {
  ElMessageBox.confirm(`您确定删除id为${id}的数据吗`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      request.post("/files/delete", { id }).then((res) => {
        ElMessage({
          type: "success",
          message: res.msg,
        });
        if (res.code == 200) {
          initData();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
const goDetail = (url) => {
  window.open(
    "https://file.keking.cn/onlinePreview?url=" + encodeURIComponent(window.btoa(url))
  );
};
const handleSizeChange = (limit) => {
  state.searchData.limit = limit;
  initData();
};
const changeSearch = (val) => {
  initData();
};
const importDataDialogVisible = ref(false);
const importData = () => {
  importDataDialogVisible.value = true;
};
let fileList = reactive([]);
const UploadFileUrl = () => {
  // 因为action参数是必填项，我们使用二次确认进行文件上传时，
  // 直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
  return "";
};

// 文件超出个数限制时的钩子
const handleExceed = () => {
  ElMessage({
    type: "warning",
    message: "一次最多只能上传1个文件哦",
  });
};
//  // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const fileChange = (file, list) => {
  fileList = list;
};
const uploadFileBtn = () => {
  let fileInfo = fileList[0].raw;
  let size = fileInfo.size / 1024 / 1024;
  console.log("++++",size)
  let type = fileInfo.name.substring(fileInfo.name.lastIndexOf(".") + 1);
  // 判断文件类型
  //   if (!(type == 'png' || type == 'jepg')) {
  //     ElMessage({
  //       type: 'warning',
  //       message: '只能上传后缀是.xlsx或者.xls的文件',
  //     })
  //     return
  //   }
  // 限制上传文件的大小
  if (size > 10) {
    ElMessage({
      type: "warning",
      message: "文件大小不得超过10M",
    });
    return;
  }
  if (fileList.length < 1) {
    ElMessage({
      type: "warning",
      message: "请先上传文件",
    });
    return;
  }
  let multipartFile = new FormData();
  multipartFile.append("multipartFile", fileList[0].raw);
  let params = {
    isFile: true,
    multipartFile,
  };
  request.post("/files/uploadFile", params).then((res) => {
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "上传成功",
      });
    }
    importDataDialogVisible.value = false;
  });
};
const downloadFile = (url) =>{
  window.open(url)
}
</script>
